package com.lyl.security.module.security.service;

import cn.hutool.core.lang.Assert;
import com.lyl.security.common.exception.BizException;
import com.lyl.security.common.result.ErrorCode;
import com.lyl.security.module.security.model.details.LoginUser;
import com.lyl.security.module.system.entity.SysUser;
import com.lyl.security.module.system.service.PermissionsService;
import com.lyl.security.module.system.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author Mr.Luo
 * @date 2022-09-14 11:28
 * @desc
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final SysUserService sysUserService;
    private final PermissionsService permissionsService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getByUsername(username);
        Assert.notNull(sysUser, () -> new BizException(ErrorCode.UNAUTHORIZED, "找不到对应的用户"));
        return new LoginUser(sysUser,permissionsService.getMenuPermsByUserId(sysUser.getUserId()));
    }
}
